#!/bin/bash

# Name can be overwritten, as Metricbeat is also a library
BEATNAME?=metricbeat
BEAT_DESCRIPTION?=Metricbeat sends metrics to Elasticsearch.
SYSTEM_TESTS=true
TEST_ENVIRONMENT?=true
GOPACKAGES=$(shell go list ${BEAT_DIR}/... | grep -v /vendor/)
ES_BEATS?=..

TARGETS?="windows/amd64 windows/386 darwin/amd64"
TARGETS_OLD?="linux/amd64 linux/386"
CGO=true

# Metricbeat can only be cross-compiled on platforms not requiring CGO.
GOX_OS=solaris netbsd linux windows
GOX_FLAGS='-arch=amd64 386 arm ppc64 ppc64le'


include ${ES_BEATS}/libbeat/scripts/Makefile

# Collects all module dashboards
.PHONY: kibana
kibana:
	# To not remove index-pattern as generated by update
	-rm -r _meta/kibana/dashboard _meta/kibana/search _meta/kibana/visualization
	mkdir -p _meta/kibana
	-cp -r module/*/_meta/kibana _meta/

# Collects all module and metricset fields
.PHONY: fields
fields:
	mkdir -p _meta/
	cat ${ES_BEATS}/metricbeat/_meta/fields.common.yml > _meta/fields.generated.yml
	. ${PYTHON_ENV}/bin/activate; python ${ES_BEATS}/metricbeat/scripts/fields_collector.py >> _meta/fields.generated.yml

# Collects all module docs
.PHONY: collect-docs
collect-docs: python-env
	-rm -rf docs/modules
	mkdir -p docs/modules
	. ${PYTHON_ENV}/bin/activate; python ${ES_BEATS}/metricbeat/scripts/docs_collector.py --beat ${BEATNAME}

# Collects all module configs
.PHONY: configs
configs: python-env
	. ${PYTHON_ENV}/bin/activate; python ${ES_BEATS}/metricbeat/scripts/config_collector.py --beat ${BEATNAME} $(PWD) > _meta/beat.yml
	. ${PYTHON_ENV}/bin/activate; python ${ES_BEATS}/metricbeat/scripts/config_collector.py --beat ${BEATNAME} --full $(PWD) > _meta/beat.full.yml

# Generates imports for all modules and metricsets
.PHONY: imports
imports:
	mkdir -p include
	python ${ES_BEATS}/metricbeat/scripts/generate_imports.py ${BEAT_DIR} ${BEATNAME} > include/list.go

# This is called by the beats packer before building starts
.PHONY: before-build
before-build:
	# disable the system/load metricset on windows
	sed -i.bk 's/- load/#- load/' $(PREFIX)/metricbeat-win.yml
	rm $(PREFIX)/metricbeat-win.yml.bk
	sed -i.bk 's/- load/#- load/' $(PREFIX)/metricbeat-win.full.yml
	rm $(PREFIX)/metricbeat-win.full.yml.bk

# Runs all collection steps and updates afterwards
.PHONY: collect
collect: fields collect-docs configs kibana imports

# Creates a new metricset. Requires the params MODULE and METRICSET
.PHONY: create-metricset
create-metricset:
	python ${ES_BEATS}/metricbeat/scripts/create_metricset.py --path=$(PWD) --es_beats=$(ES_BEATS) --module=$(MODULE) --metricset=$(METRICSET)


# Generates the data.json example documents
.PHONY: generate-json
generate-json: build-image
	 ${DOCKER_COMPOSE} run beat go test -tags=integration github.com/elastic/beats/metricbeat/module/... -data

